package com.community.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DBUtil {

    private static DataSource dataSource;

    static {
        try {

            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:comp/env");

            dataSource = (DataSource)envContext.lookup("jdbc/community_healthDS");
        } catch (NamingException e) {
            throw new RuntimeException("JNDI数据源初始化失败", e);
        }
    }


    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            throw new SQLException("数据源未初始化");
        }
        return dataSource.getConnection();
    }
}